//   Tato 
//   var CLIENT_ID = '68249450936-a3fk9gnmcdk663e5n589e4lem0b47i5n.apps.googleusercontent.com';
//   Prod 
       var CLIENT_ID = '68249450936-co3lni5kq42r79p1o0nqam04qpq2coaj.apps.googleusercontent.com';
//   Laure
    //var CLIENT_ID = '68249450936-5buegmdeclot82q49j3aail85e20258e.apps.googleusercontent.com';

// ------ Take photo -------- //

document.addEventListener("appMobi.camera.picture.add",onSuccess); 
document.addEventListener("appMobi.camera.picture.busy",onSuccess); 
document.addEventListener("appMobi.camera.picture.cancel",onSuccess); 

function capturePhoto() {
  AppMobi.camera.takePicture(50,false,"jpg");
}

var img = new Image();
var filename = "";
function onSuccess(evt) {
 	if (evt.success == true) {	
  		Nav.next("edit");  
		img.src = AppMobi.camera.getPictureURL(evt.filename);
		img.onload = function(){
  			// var imageData = Filters.getPixels(img)
  			filename = evt.filename;
			var canvas = document.getElementById("cv01");
			canvas.width = img.width;
			canvas.height = img.height;

			var context = canvas.getContext("2d");
		  	context.drawImage(img, 0, 0);
	  }
  }
  else   {
	if (evt.message != undefined) 	{
		alert(evt.message);
	} else {
		alert("error capturing picture");
	}
  }
}

function injectLocationAndUpload(blob){
	navigator.geolocation.getCurrentPosition(
		//success
		function(p){
			blob.latitude = p.coords.latitude;
			blob.longitude = p.coords.longitude;
			uploadFile(blob);
		},
		//error
		function(){
			uploadFile(blob);
		}
	);	
	
}

// ------ Upload to GDrive -------- //

  var SCOPES = [
	  'https://www.googleapis.com/auth/drive.file',
	  'https://www.googleapis.com/auth/userinfo.email',
	  'https://www.googleapis.com/auth/userinfo.profile',
	  // Add other scopes needed by your application.
	];

  /**
   * Called when the client library is loaded to start the auth flow.
   */
  function handleClientLoad() {
	window.setTimeout(checkAuth, 1);
  }

  /**
   * Check if the current user has authorized the application.
   */
  function checkAuth() {
	gapi.auth.authorize(
		{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},
		handleAuthResult);
  }

  /**
   * Called when authorization server replies.
   *
   * @param {Object} authResult Authorization result.
   */
  function handleAuthResult(authResult) {
	var authButton = document.getElementById('authorizeButton');
	var capture = $("[data-action=capture]");
	authButton.style.display = 'none';
	capture.hide();
	if (authResult && !authResult.error) {
	  // Access token has been successfully retrieved, requests can be sent to the API.
	  capture.show();
	  capture.on("click", capturePhoto);
	} else {
	  // No access token could be retrieved, show the button to start the authorization flow.
	  authButton.style.display = 'block';
	  authButton.onclick = function() {
		  gapi.auth.authorize(
			  {'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': false},
			  handleAuthResult);
		  return false;
	  };
	}
  }

  /**
   * Start the file upload.
   *
   * @param {Object} evt Arguments from the file selector.
   */
  function uploadFile(file) {
//	alert('Uploading file...');
	gapi.client.load('drive', 'v2', function() {
	  insertFile(file, 
		 function(cb){
			 if(cb) {
				Nav.back("<img src='images/success.png'>" +"Upload Complete");
				setTimeout(function() {
					$(".msg").html("");
				}, 3000);
			 }
			 else {
			 	console.log(cb);
			 }
		 });
	});
  }

  /**
   * Insert new file.
   *
   * @param {File} fileData File object to read data from.
   * @param {Function} callback Function to call when the request is complete.
   */
  function insertFile(fileData, callback) {
//	alert("Entering insertFile...");
	const boundary = '-------314159265358979323846';
	const delimiter = "\r\n--" + boundary + "\r\n";
	const close_delim = "\r\n--" + boundary + "--";

	var reader = new FileReader();
	reader.readAsBinaryString(fileData);
//	  alert('aftere readAsBinaryString, before onload...');
	reader.onload = function(e) {
//	  alert('reader onload');
	  var contentType = fileData.type || 'application/octet-stream';
	  var description = (fileData.latitude && fileData.longitude) ? 'lat:'+fileData.latitude+',long:'+fileData.longitude : 'Position not specified';
	  var metadata = {
		'title': fileData.name,
		'mimeType': contentType,
	    'description': description
	  };

	  var base64Data = btoa(reader.result);
	  var multipartRequestBody =
		  delimiter +
		  'Content-Type: application/json\r\n\r\n' +
		  JSON.stringify(metadata) +
		  delimiter +
		  'Content-Type: ' + contentType + '\r\n' +
		  'Content-Transfer-Encoding: base64\r\n' +
		  '\r\n' +
		  base64Data +
		  close_delim;

	  var request = gapi.client.request({
		  'path': '/upload/drive/v2/files',
		  'method': 'POST',
		  'params': {'uploadType': 'multipart'},
		  'headers': {
			'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
		  },
		  'body': multipartRequestBody});
	  if (!callback) {
		callback = function(file) {
		  console.log(file)
		};
	  }
	  request.execute(callback);
	}
  }